package com.culture.java.online.education.platform.business.demo.controller;

import com.culture.java.online.education.platform.business.demo.service.StudentService;
import com.culture.java.online.education.platform.common.base.response.R;
import com.culture.java.online.education.platform.data.demo.entity.Student;
import com.culture.java.online.education.platform.data.demo.vo.input.StudentSaveOrModifyVo;
import com.culture.java.online.education.platform.data.demo.vo.output.StudentListVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("student")
@Slf4j
public class StudentController {

    @Autowired
    private StudentService studentService;

    @PostMapping("save")
    public R save(@RequestBody @Validated(StudentSaveOrModifyVo.Insert.class) StudentSaveOrModifyVo studentSaveOrModifyVo) {
        log.debug("前端传过来的VO对象 - {}", studentSaveOrModifyVo);
        Student student = new Student();
        // 将Vo对象中的属性拷贝给Entity对象
        BeanUtils.copyProperties(studentSaveOrModifyVo, student);

        boolean b = studentService.save(student);
        return R.success(b);
    }

    @GetMapping("one/{id}")
    public R one(@PathVariable Integer id) {
        Student student = studentService.getById(id);
        StudentListVo studentListVo = new StudentListVo();
        BeanUtils.copyProperties(student, studentListVo);
        return R.success(studentListVo);
    }

    @GetMapping("list")
    public R list() {
        List<Student> studentList = studentService.list();
        StudentListVo studentListVo = new StudentListVo();
        List<StudentListVo> studentListVoList = new ArrayList<>();
        for (Student student : studentList) {
            BeanUtils.copyProperties(student, studentListVo);
            studentListVoList.add(studentListVo);
        }
        return R.success(studentListVoList);
    }

    @PutMapping("modify")
    public R modify(@RequestBody @Validated(StudentSaveOrModifyVo.Update.class) StudentSaveOrModifyVo studentSaveOrModifyVo) {
        Student student = new Student();
        // 将Vo对象中的属性拷贝给Entity对象
        BeanUtils.copyProperties(studentSaveOrModifyVo, student);
        boolean b = studentService.updateById(student);
        return R.success(b);
    }

}
